//
//  AppDelegate.swift
//  XDweibo
//
//  Created by HanXingda on 15/6/23.
//  Copyright © 2015年 韩兴达. All rights reserved.
//

import UIKit
import AFNetworking
var sharedUserAccount = UserAccount.loadAccount()
//切换跟控制器的通知
let SwitchViewControllerNotifocation = "SwitchRootViewController"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.rootViewController = defaultViewController()
        //设置网络
        setupNetWork()
        //设置外观
        setupAppearance()
        //打印用户信息
        print(sharedUserAccount)
        window?.makeKeyAndVisible()
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: SwitchViewControllerNotifocation, object: nil)
        
        return true
    }
    
    func switchViewController(n:NSNotification) {
        let isMainVC = n.object as! Bool
        window?.rootViewController = isMainVC ? MainTarBarController() : WelcomeViewController()
    }
    private func defaultViewController() -> UIViewController {
        //判断用户是否登录
        if sharedUserAccount != nil {
           //如果登录，判断是否更新
            return isNewUpDate() ? NewFeatureCollectionController() : WelcomeViewController()
        }
        return MainTarBarController()
    }
    func isNewUpDate() -> Bool {
        //获取当前的版本号
        let currentVeision = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVeision)
        //获取之前的版本号，从偏好设置中读取
        let versionKey = "versionKey"
        let prefixVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        //将当前版本写入偏好
        NSUserDefaults.standardUserDefaults().setDouble(version!, forKey: versionKey)
        return version > prefixVersion
        
    }
    //设置网络
    func setupNetWork() {
        //设置网络指示器
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        //设置网络缓存
        let urlCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        NSURLCache.setSharedURLCache(urlCache)
    }
    func setupAppearance() {
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        UIBarButtonItem.appearance().tintColor = UIColor.orangeColor()

    }

}

